package com._9xcloud.leaverequest.web.config;

import com._9xcloud.leaverequest.domain.Student;
import com._9xcloud.leaverequest.domain.Teacher;
import com._9xcloud.leaverequest.domain.UserRole;
import com._9xcloud.leaverequest.service.StudentService;
import com._9xcloud.leaverequest.service.TeacherService;
import com._9xcloud.leaverequest.web.security.AuthenticationTokenProcessingFilter;
import com._9xcloud.leaverequest.web.security.UnauthorizedEntryPoint;
import com._9xcloud.leaverequest.web.security.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.util.matcher.ELRequestMatcher;

/**
 * Created by hyq on 2015/6/11.
 */
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityContextConfiguration extends WebSecurityConfigurerAdapter{
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.addFilterBefore(authenticationTokenProcessingFilter(), DefaultLoginPageGeneratingFilter.class);
        http.antMatcher("/api/**");
        http.authorizeRequests().antMatchers("/api/student/login").permitAll();
        http.authorizeRequests().antMatchers("/api/teacher/login").permitAll();
        http.authorizeRequests().antMatchers("/api/teacher/**").hasRole(Teacher.USER_ROLE_NAME);
        http.authorizeRequests().antMatchers("/api/student/**").hasRole(Student.USER_ROLE_NAME);
    }

    @Override
    protected UserDetailsService userDetailsService() {
        return userService();
    }

    @Bean
    public AuthenticationTokenProcessingFilter authenticationTokenProcessingFilter() {
        return new AuthenticationTokenProcessingFilter(userService());
    }

    @Bean
    public UnauthorizedEntryPoint unauthorizedEntryPoint() {
        return new UnauthorizedEntryPoint();
    }

    @Bean
    public UserService userService() {
        return new UserService(teacherService, studentService);
    }
}
